const mongoose = require('mongoose');

const GroupSchema = new mongoose.Schema(
   {
      group_name: {
         type: String,
         required: [true, '组织名称不能为空'],
      },
      budget: {
         type: Number,
         default: 0,
      },
      desc: {
         type: String,
      },
      createdBy: {
         type: mongoose.Types.ObjectId,
         ref: 'User',
         required: [true, '创建人不能为空'],
      },
      members: {
         type: [mongoose.Types.ObjectId],
         ref: 'User',
         default: [],
      },
   },
   {
      timestamps: true,
   }
);

GroupSchema.pre('save', function (next) {
   const members = this.members;
   this.members = [...new Set(members)]; // 移除数组中的重复项
   next();
});

module.exports = mongoose.model('Group', GroupSchema);
